package com.application.lucky.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Author: wizChen
 * Date: 2017-02-01 20:52
 * Description: help to get the current activity of the application
 */
public class TopActivityManager implements Application.ActivityLifecycleCallbacks {
    private WeakReference<Activity> mCurrentActivity;
    private List<Activity> activityList;
    private boolean background = true;
    private ActivityCallBacks backs;
    public void setCallBacks(ActivityCallBacks backs){
        this.backs = backs;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        activityList.add(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        setCurrentActivity(activity);
        background = false;
        if (backs!=null) {
            backs.onResume();
        }
    }

    @Override
    public void onActivityPaused(Activity activity) {
        background = true;
        if (backs!=null) {
            backs.onPause();
        }
    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        activityList.remove(activity);
    }

    private static class TopActivityManagerHolder {
        private static final TopActivityManager INSTANCE = new TopActivityManager();
    }

    public static TopActivityManager getInstance() {
        return TopActivityManagerHolder.INSTANCE;
    }

    private TopActivityManager() {
        activityList = Collections.synchronizedList(new ArrayList<Activity>());
    }

    public Activity getCurrentActivity() {
        Activity currentActivity = null;
        if (mCurrentActivity != null) {
            currentActivity = mCurrentActivity.get();
        }
        return currentActivity;
    }

    public void setCurrentActivity(Activity activity) {
        mCurrentActivity = new WeakReference<>(activity);
    }

    public boolean isBackground() {
        return background;
    }

    public void setBackground(boolean background) {
        this.background = background;
    }

    public List<Activity> getActivityList(){
        return activityList;
    }


    public void exit() {
        Iterator<Activity> iterator = activityList.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next();
            activity.finish();
            iterator.remove();
        }
        activityList.clear();
    }
    public interface ActivityCallBacks{
        void onResume();
        void onPause();
    }
}
